package autocode

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/autocode"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
    autoCodeReq "github.com/flipped-aurora/gin-vue-admin/server/model/autocode/request"
)

type AttributeService struct {
}

// CreateAttribute 创建Attribute记录
// Author [piexlmax](https://github.com/piexlmax)
func (attributeService *AttributeService) CreateAttribute(attribute autocode.Attribute) (err error) {
	err = global.GVA_DB.Create(&attribute).Error
	return err
}

// DeleteAttribute 删除Attribute记录
// Author [piexlmax](https://github.com/piexlmax)
func (attributeService *AttributeService)DeleteAttribute(attribute autocode.Attribute) (err error) {
	err = global.GVA_DB.Delete(&attribute).Error
	return err
}

// DeleteAttributeByIds 批量删除Attribute记录
// Author [piexlmax](https://github.com/piexlmax)
func (attributeService *AttributeService)DeleteAttributeByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]autocode.Attribute{},"id in ?",ids.Ids).Error
	return err
}

// UpdateAttribute 更新Attribute记录
// Author [piexlmax](https://github.com/piexlmax)
func (attributeService *AttributeService)UpdateAttribute(attribute autocode.Attribute) (err error) {
	err = global.GVA_DB.Save(&attribute).Error
	return err
}

// GetAttribute 根据id获取Attribute记录
// Author [piexlmax](https://github.com/piexlmax)
func (attributeService *AttributeService)GetAttribute(id uint) (err error, attribute autocode.Attribute) {
	err = global.GVA_DB.Where("id = ?", id).First(&attribute).Error
	return
}

// GetAttributeInfoList 分页获取Attribute记录
// Author [piexlmax](https://github.com/piexlmax)
func (attributeService *AttributeService)GetAttributeInfoList(info autoCodeReq.AttributeSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&autocode.Attribute{})
    var attributes []autocode.Attribute
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.Name != "" {
        db = db.Where("name LIKE ?","%"+ info.Name+"%")
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }
	err = db.Limit(limit).Offset(offset).Find(&attributes).Error
	return err, attributes, total
}
